const multer = require('multer')
const path = require('path')

var sd = require('silly-datetime'); 
var mkdirp = require('mkdirp'); 

const md5 = require('md5')

const tools = {
  multer() {
    // var upload = multer({ dest: 'static/uploads' }) // 上传之前目录必须存在
    const storage = multer.diskStorage({
      // 配置上传的目录
      destination: async (req, file, cb) => {
        // 1. 获取当前日期
        let day = sd.format(new Date(), 'YYYYMMDD');
        // 2. 按照日期生成图片存储目录
        let dir = path.join('static/uploads', day) 
        await mkdirp(dir); // 异步方法
        // cb(null, 'static/uploads')
        cb(null, dir)
      },
      // 修改上传后的问题件名
      filename: function (req, file, cb) {
        // 1. 获取后缀名
        let extname = path.extname(file.originalname)
        // 2. 根据时间戳生成文件名
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9) + extname
        cb(null, file.fieldname + '-' + uniqueSuffix)
      }
    })

    const upload = multer({ storage: storage })

    return upload
  },
  md5(str) {
    return md5(str)
  },
  getUnix() {
    var d = new Date()
    return d.getTime()
  }
}

module.exports = tools